# -*- coding: utf-8 -*-
from urllib import request, parse, error
import time
import random
import hashlib
import json
import gzip

'''使用urlopen(request_url, data)发送参数'''


def fun1():
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    i = input("Translation for: ")

    u = 'fanyideskweb'
    d = i
    f = str(int(time.time() * 1000) + random.randint(0, 10))
    c = 'ebSeFb%=XZ%T[KZ)c(sy!'
    # print(f)
    md5 = hashlib.md5()
    md5.update(u.encode('utf-8'))
    md5.update(d.encode('utf-8'))
    md5.update(f.encode('utf-8'))
    md5.update(c.encode('utf-8'))

    sign = md5.hexdigest()
    data = {
        'i': i,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': f,
        'sign': sign,
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTIME',
        'typoResult': 'false'
    }
    # print(sign)
    # 使用urlencode方法转换标准格式
    data = parse.urlencode(data).encode()
    # print(data)
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '200',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'OUTFOX_SEARCH_USER_ID_NCOO=333123599.1556535; OUTFOX_SEARCH_USER_ID="-1205270731@10.169.0.84"; JSESSIONID=aaaYk8V1ISebd5af0fryw; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcWJ8vzLbNn1bwYBKtyw; ___rl__test__cookies=1537926668998',
        'Host': 'fanyi.youdao.com',
        'Origin': 'http://fanyi.youdao.com',
        'Referer': 'http://fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'

    }
    # 传递Request对象和转换完格式的数据
    request_url = request.Request(url, data=data, headers=headers)

    try:
        response = request.urlopen(request_url)
        # encoding = response.info().get('Content-Encoding')
        # 200 获取response成功
        print(response.getcode())
        # 读取信息并解码， 转化为json格式
        result = gzip.decompress(response.read()).decode('utf-8')
        # print(result)
        json_result = json.loads(result)
        # print(json_result)
        translation_result = json_result['translateResult'][0][0]['tgt']
        # 打印翻译信息
        print('翻译的结果是： %s' % translation_result)
    except error.HTTPError as e:
        print('HTTPError: {}'.format(e))
        print('HTTPError: ' + e.reason)
    except error.URLError as e:
        print('URLError: {}'.format(e))
        print('URLError: ' + e.reason)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    fun1()
